import classNames from 'classnames'
import React, { useEffect, useState } from 'react'
import styles from './index.module.less'

interface TabsProps { 
  stretch?: boolean
  className?: string
  activeKey?: string
  defaultActiveKey?: string
  showTabIcon?: boolean
  onChange?: (key: string, index: number) => void
  tabMap: Map<string, React.ReactNode>
}

function Tabs(props: TabsProps) {
  const { tabMap, stretch = true, showTabIcon=false, className, activeKey: propsActiveKey, defaultActiveKey, onChange } = props
  
  const [activeKey, setActiveKey] = useState<string>(defaultActiveKey || Array.from(tabMap)[0]?.[0])

  useEffect(() => { 
    propsActiveKey && setActiveKey(propsActiveKey)
  }, [propsActiveKey])

  return (
    <div className={classNames(styles.tabs, className, { 'stretch': stretch })}>
      {Array.from(tabMap).map(([key, title], index) => {
        const isActive = activeKey === key
        return (
          <div
            key={key}
            className={classNames(styles.tabsItem, { 'active': isActive })}
            onClick={() => {
              if (activeKey !== key) {
                if (!propsActiveKey) { 
                  setActiveKey(key)
                }
                onChange && onChange(key, index)
              }
            }}
          >
            {title}
            { showTabIcon && <div className={index==0 ? styles.tabLeft :styles.tabRight}></div>}
            <div className={styles.after}></div>
          </div>
        )
      })}
    </div>
  )
}

export default Tabs